#Boa:FramePanel:WXVISPANEL

import wx
import os, sys
import shutil
import time
import math
#from pysqlite2 import dbapi2 as sqlite
import vtk
import vtktudoss
import superthread

def create(parent, bla):
    return wxVisPanel(parent,  bla)

[wxID_WXVISPANEL, wxID_FRAME1SLICER,  
wxID_FRAME1VISUALISE, wxID_FRAME1ADJUSTVOLUME,
wxID_FRAME1VISUALISEBONE,wxID_CLEARFEEDBACK,  
 wxID_VOLUMEVISUALISE, wxID_VOLUMESHOWBONE, wxID_VOLUMESHOWMUSCLE,
 wxID_VOLUMESHOWSKIN, wxID_WXFRAME1VISPANEL1, wxID_FRAME1SHOWHUMERUS, 
 wxID_FRAME1SHOWSCAPULA, wxID_FRAME1SHOWHUMERUSPROSTHESIS, 
 wxID_FRAME1SHOWSCAPULAPROSTHESIS, wxID_FRAME1DECIMATEDBONE,
 wxID_FRAME1VOLLISTBOX, wxID_FRAME1STOREVOLUME, wxID_FRAME1ADDVOLUME,
 wxID_CAMKEYFRAME, wxID_CAMPLAY, wxID_CAMCLEAR, wxID_RECORD
] = [wx.NewId() for _init_ctrls in range(23)]

class wxVisPanel(wx.Panel):
    
    volume_path = ''
    volume_changed = False
    volume_counter = 0
    threshold=10.0
    pathActor = vtk.vtkActor()
    polydata = vtk.vtkPolyData()    
    picker = vtk.vtkCellPicker()
    picker.SetTolerance(0.005)
    outlineActor = vtk.vtkActor()
    
    def _init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=wxID_WXVISPANEL, name='', parent=prnt,
              pos=wx.Point(0, 0), size=wx.Size(200, 500), style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(192, 73))

        self.visualiseBone = wx.CheckBox(id=wxID_FRAME1VISUALISEBONE,
              label=u'Surface Models',
              name='ShowBone', parent=self, 
              pos=wx.Point(10, 10), size=wx.Size(135, 24), style=0)
        self.visualiseBone.SetValue(False)   
        self.visualiseBone.Enable(False)
        self.visualiseBone.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.visualiseBone)
        
        self.DecimatedBone = wx.CheckBox(id=wxID_FRAME1DECIMATEDBONE,
              label=u'Decimated',
              name='DecimatedBone', parent=self, 
              pos=wx.Point(145, 10), size=wx.Size(90, 24), style=0)
        self.DecimatedBone.SetValue(True)   
        self.DecimatedBone.Enable(True)
        self.DecimatedBone.Bind(wx.EVT_CHECKBOX, self.OnDecimatedChange, self.DecimatedBone)
        
        self.showHumerus = wx.CheckBox(id=wxID_FRAME1SHOWHUMERUS,
              label=u'Humerus',
              name='ShowHum', parent=self, 
              pos=wx.Point(25, 30), size=wx.Size(100, 24), style=0)
        self.showHumerus.SetValue(True)   
        self.showHumerus.Enable(False)
        self.showHumerus.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showHumerus)
        
        self.showScapula = wx.CheckBox(id=wxID_FRAME1SHOWSCAPULA,
              label=u'Scapula',
              name='ShowScap', parent=self, 
              pos=wx.Point(25, 50), size=wx.Size(100, 24), style=0)
        self.showScapula.SetValue(True)   
        self.showScapula.Enable(False)
        self.showScapula.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showScapula)
        
        self.showHumerusProsthesis = wx.CheckBox(id=wxID_FRAME1SHOWHUMERUSPROSTHESIS,
              label=u'Prosthesis',
              name='ShowHumPros', parent=self, 
              pos=wx.Point(125, 30), size=wx.Size(130, 24), style=0)
        self.showHumerusProsthesis.SetValue(False)   
        self.showHumerusProsthesis.Enable(False)
        self.showHumerusProsthesis.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showHumerusProsthesis)
        
        self.showGlenoidProsthesis = wx.CheckBox(id=wxID_FRAME1SHOWSCAPULAPROSTHESIS,
              label=u'Prosthesis',
              name='ShowScapPros', parent=self, 
              pos=wx.Point(125, 50), size=wx.Size(130, 24), style=0)
        self.showGlenoidProsthesis.SetValue(False)   
        self.showGlenoidProsthesis.Enable(False)
        self.showGlenoidProsthesis.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showGlenoidProsthesis)
        
        self.clearFeedback = wx.CheckBox(id=wxID_CLEARFEEDBACK,
              label=u'Landmarks',
              name='ShowCurv', parent=self, 
              pos=wx.Point(10, 70), size=wx.Size(176, 24), style=0)
        self.clearFeedback.SetValue(False) 
        #self.clearFeedback.Enable(False)
        self.clearFeedback.Bind(wx.EVT_CHECKBOX, self.OnclearFeedback, self.clearFeedback)
        
        self.showSlicer = wx.CheckBox(id=wxID_FRAME1SLICER,
              label=u'Show Slicer', name=u'Display Slicer', parent=self,
              pos=wx.Point(10, 90), size=wx.Size(176, 24), style=0)
        self.showSlicer.Bind(wx.EVT_CHECKBOX, self.OnShowSlicer, self.showSlicer)
        self.showSlicer.SetValue(False)
        self.showSlicer.Enable(False)        
        
        self.showVolume = wx.CheckBox(id=wxID_VOLUMEVISUALISE,
              label=u'Display Volume',
              name='volume_check', parent=self, 
              pos=wx.Point(10, 110), size=wx.Size(176, 24), style=0)   
        self.showVolume.Bind(wx.EVT_CHECKBOX, self.OnShowVolumeChange, self.showVolume)
        self.showVolume.Enable(False)
        self.showVolume.SetValue(False)

        self.showBone = wx.CheckBox(id=wxID_VOLUMESHOWBONE,
              label=u'Show Bone Volume',
              name='ShowBone', parent=self, 
              pos=wx.Point(25, 130), size=wx.Size(176, 24), style=0)
        self.showBone.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showBone)

        self.showMuscle = wx.CheckBox(id=wxID_VOLUMESHOWMUSCLE,
              label=u'Show Muscle Volume',
              name='ShowMuscle', parent=self, 
              pos=wx.Point(25, 150), size=wx.Size(176, 24), style=0)
        self.showMuscle.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showMuscle)     
        
        self.showSkin = wx.CheckBox(id=wxID_VOLUMESHOWSKIN,
              label=u'Show Skin Volume',
              name='ShowSkin', parent=self, 
              pos=wx.Point(25, 170), size=wx.Size(176, 24), style=0)
        self.showSkin.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showSkin)    
        
        self.showSlicer.SetValue(False)
        self.showVolume.SetValue(False)
        self.showMuscle.SetValue(True)
        self.showMuscle.Enable(False)
        self.showBone.SetValue(True)
        self.showBone.Enable(False)
        self.showSkin.SetValue(True)
        self.showSkin.Enable(False)

        #~ self.slider1 = wx.Slider(self, -1, 0, 0, 100, (10, 210), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)        
        #~ self.slider1.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted)

        #~ self.slider2 = wx.Slider(self, -1, 0, 0, 100, (10, 260), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)        
        #~ self.slider2.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted)

        #~ self.slider3 = wx.Slider(self, -1, 0, 0, 100, (10, 310), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)        
        #~ self.slider3.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted)
        
        self.VolumeListbox = wx.ListBox(self, id=wxID_FRAME1VOLLISTBOX, pos=wx.Point(10, 370), size= wx.Size(200, 70), 
              choices='', style=0, name=u'VolListbox') 
        self.VolumeListbox.SetAutoLayout(False)
        self.VolumeListbox.Bind(wx.EVT_LISTBOX, self.VolumeListboxClicked,
              id = wxID_FRAME1VOLLISTBOX)    
              
        self.StoreVolume = wx.Button(id=wxID_FRAME1STOREVOLUME,
              label=u'Save Volume', name=u'SaveVolume', parent=self,
              pos=wx.Point(10, 445), size=wx.Size(200, 24), style=0)
        self.StoreVolume.SetAutoLayout(False)
        self.StoreVolume.Bind(wx.EVT_BUTTON, self.OnStoreVolume,
              id=wxID_FRAME1STOREVOLUME)
        self.StoreVolume.Enable(False)
              
        self.AddVolume = wx.Button(id=wxID_FRAME1ADDVOLUME,
              label=u'Add Volume', name=u'LoadVolume', parent=self,
              pos=wx.Point(10, 470), size=wx.Size(200, 24), style=0)
        self.AddVolume.SetAutoLayout(False)
        self.AddVolume.Bind(wx.EVT_BUTTON, self.OnLoadVolume,
              id=wxID_FRAME1ADDVOLUME)
        self.AddVolume.Enable(False)
              
        self.CamKeyframe = wx.Button(id=wxID_CAMKEYFRAME,
              label=u'Cam Keyframe', name=u'camkey', parent=self,
              pos=wx.Point(10, 505), size=wx.Size(97, 24), style=0)
        self.CamKeyframe.SetAutoLayout(False)
        self.CamKeyframe.Bind(wx.EVT_BUTTON, self.OnCamKeyframe,
              id=wxID_CAMKEYFRAME)
              
        self.CamPlay = wx.Button(id=wxID_CAMPLAY,
              label=u'Play Motion', name=u'camplay', parent=self,
              pos=wx.Point(103, 505), size=wx.Size(107, 24), style=0)
        self.CamPlay.SetAutoLayout(False)
        self.CamPlay.Bind(wx.EVT_BUTTON, self.OnCamPlay,
              id=wxID_CAMPLAY)
              
        self.CamClear = wx.Button(id=wxID_CAMCLEAR,
              label=u'Clear', name=u'clear', parent=self,
              pos=wx.Point(10, 529), size=wx.Size(200, 24), style=0)
        self.CamClear.SetAutoLayout(False)
        self.CamClear.Bind(wx.EVT_BUTTON, self.OnCamClear,
              id=wxID_CAMCLEAR)
              
        self.RecordView = wx.ToggleButton(id=wxID_RECORD,
              label=u'Record View', name=u'record', parent=self,
              pos=wx.Point(10, 320), size=wx.Size(200, 24), style=0)
        self.RecordView.SetAutoLayout(False)
        self.RecordView.Bind(wx.EVT_TOGGLEBUTTON, self.OnRecordViewToggle,
              id=wxID_RECORD)

        
    def __init__(self, parent, id, pos, size, style, name, bla):
        self.parent = bla        
        self._init_ctrls(parent)
        self.opacityTransferFunction = vtk.vtkPiecewiseFunction()
        self.rendervolume = vtk.vtkVolume()
        self.volumecollection = vtk.vtkCollection()
        self.volumecollectionwindowlevels = []
        self.volumecollectioncolortables = []
        self.previously_selected = 0
        
        self.lastsliceindex = 0
        self.planeWidget = vtk.vtkImagePlaneWidget()  
        self.planeWidget2 = vtk.vtkImagePlaneWidget()
        self.planeWidget2.DisplayTextOff()
        self.planeWidget2.SetTextureInterpolate(1)
        self.planeWidget2.TextureVisibilityOn()                            
        
        intevent = self.planeWidget.AddObserver("InteractionEvent", self.UpdatePlaneWidget2)
        
        self.InitializeKeyframes()
        
    def OnValuesAdjusted(self, event):
        pass
        
    def InitializeKeyframes(self):
        self.posx = vtk.vtkCardinalSpline()
        self.posy = vtk.vtkCardinalSpline()
        self.posz = vtk.vtkCardinalSpline()
        self.clip1 = vtk.vtkCardinalSpline()
        self.clip2 = vtk.vtkCardinalSpline()
        self.viewangle = vtk.vtkCardinalSpline()
        self.viewupx = vtk.vtkCardinalSpline()
        self.viewupy = vtk.vtkCardinalSpline()
        self.viewupz = vtk.vtkCardinalSpline()
        self.focalx = vtk.vtkCardinalSpline()
        self.focaly = vtk.vtkCardinalSpline()
        self.focalz = vtk.vtkCardinalSpline()
        
    def OnCamClear(self, event):
        self.InitializeKeyframes()
        
    def StoreCamKeys(self):
        filename = os.path.dirname(sys.argv[0])+"/campath.txt"
        outputfile = open(filename,"w")
        outputfile.write("[main]\n")
        i = self.posx.GetNumberOfPoints()
        outputfile.write(i + "\n")
        for j in range(0,i):
        #mystr =  ("posx[] = " '%3.9f' % self.glenoidcor[0])
            outputfile.write(posx[j] + "\n")
       
        outputfile.close()    
        
        
    def OnCamKeyframe(self, event):
        currentcam = self.parent.ren1.GetActiveCamera()
        position = currentcam.GetPosition()
        i = self.posx.GetNumberOfPoints()
        self.posx.AddPoint(i, position[0])
        self.posy.AddPoint(i, position[1])
        self.posz.AddPoint(i, position[2])
        cliprange = currentcam.GetClippingRange()
        self.clip1.AddPoint(i, cliprange[0])
        self.clip2.AddPoint(i, cliprange[1])
        self.viewangle.AddPoint(i, currentcam.GetViewAngle())
        viewup = currentcam.GetViewUp()
        self.viewupx.AddPoint(i, viewup[0])
        self.viewupy.AddPoint(i, viewup[1])
        self.viewupz.AddPoint(i, viewup[2])
        focalpoint = currentcam.GetFocalPoint()
        self.focalx.AddPoint(i, focalpoint[0])
        self.focaly.AddPoint(i, focalpoint[1])
        self.focalz.AddPoint(i, focalpoint[2])
        print position
        print cliprange
        print viewup
        print focalpoint
        #~ self.StoreCamKeys()
        
    def OnCamPlay(self, event):
        resolution_factor = 30 #frames per lijn
        for i in range(0, self.posx.GetNumberOfPoints()-1):
            for p in range(1,resolution_factor):
                position = [self.posx.Evaluate(i+((p*1.0)/resolution_factor)),\
                            self.posy.Evaluate(i+((p*1.0)/resolution_factor)),\
                            self.posz.Evaluate(i+((p*1.0)/resolution_factor))]
                cliprange = [self.clip1.Evaluate(i+((p*1.0)/resolution_factor)),\
                             self.clip2.Evaluate(i+((p*1.0)/resolution_factor))]
                viewangle = self.viewangle.Evaluate(i+((p*1.0)/resolution_factor))
                viewup = [self.viewupx.Evaluate(i+((p*1.0)/resolution_factor)),\
                          self.viewupy.Evaluate(i+((p*1.0)/resolution_factor)),\
                          self.viewupz.Evaluate(i+((p*1.0)/resolution_factor))]
                focalpoint = [self.focalx.Evaluate(i+((p*1.0)/resolution_factor)),\
                              self.focaly.Evaluate(i+((p*1.0)/resolution_factor)),\
                              self.focalz.Evaluate(i+((p*1.0)/resolution_factor))]  
                currentcam = self.parent.ren1.GetActiveCamera()
                currentcam.SetPosition(position)
                currentcam.SetClippingRange(cliprange)
                currentcam.SetViewAngle(viewangle)
                currentcam.SetViewUp(viewup)
                currentcam.SetFocalPoint(focalpoint)
                self.parent.Render()
                time.sleep(0.04)
        
    def UpdatePlaneWidget2(self, event, bla):
        newindex = self.planeWidget.GetSliceIndex()
        if self.lastsliceindex != newindex:
            self.lastsliceindex = newindex
        self.planeWidget2.SetSlicePosition(self.planeWidget.GetSlicePosition()+0.2)
        #self.planeWidget2.SetSliceIndex(newindex+1)
        
    def VolumeListboxClicked(self, event):        
        sliceindex = self.planeWidget.GetSliceIndex()
        listboxindex = self.VolumeListbox.GetSelection()
        self.volumecollectionwindowlevels.pop(self.previously_selected)
        self.volumecollectioncolortables.pop(self.previously_selected)
        bla = [0,0]
        self.planeWidget.GetWindowLevel(bla)
        lut = self.planeWidget2.GetLookupTable()
        self.volumecollectionwindowlevels.insert(self.previously_selected, bla)
        self.volumecollectioncolortables.insert(self.previously_selected, lut)
        windowlevel = self.volumecollectionwindowlevels[listboxindex]
        colortable = self.volumecollectioncolortables[listboxindex]
        self.CreatePlaneWidget2(self.volumecollection.GetItemAsObject(listboxindex), windowlevel, colortable)
        self.previously_selected = listboxindex
        self.parent.Render()
        
    def SetColortable(self, lut):
        sliceindex = self.planeWidget.GetSliceIndex()
        listboxindex = self.VolumeListbox.GetSelection()
        windowlevel = self.volumecollectionwindowlevels[listboxindex]
        self.volumecollectioncolortables.pop(self.VolumeListbox.GetCount()-1)
        self.volumecollectioncolortables.append(lut)
        self.CreatePlaneWidget2(self.volumecollection.GetItemAsObject(listboxindex), windowlevel, lut)
        
    def AddVolumeToListbox(self, volume, name=None):
        self.volumecollection.AddItem(volume)
        self.volumecollectionwindowlevels.append(None)
        range = volume.GetScalarRange()              
        self.volumecollectioncolortables.append(self.GetColorTable_green(range[0], range[1]))
        if name==None:
            self.VolumeListbox.Append("volume " + str(self.volume_counter))
        else:
            self.VolumeListbox.Append(name)
        self.VolumeListbox.SetSelection(self.VolumeListbox.GetCount()-1)
        self.previously_selected = (self.VolumeListbox.GetCount()-1)
        self.volume_counter = self.volume_counter + 1
        
    def CreatePlaneWidget2(self, volume, windowlevel = None, colortable = None):
        
        self.planeWidget2.SetInput(volume)
        self.planeWidget2.SetPlaneOrientationToZAxes()
        self.planeWidget2.SetInteractor(self.parent.main.renwini)
        if windowlevel != None:
            self.planeWidget2.SetWindowLevel(windowlevel[0], windowlevel[1])
        if colortable != None:
            self.planeWidget2.SetLookupTable(colortable)
        else:
            range = volume.GetScalarRange()              
            self.planeWidget2.SetLookupTable(self.GetColorTable_bw(range[0], range[1]))        
        self.planeWidget2.SetSlicePosition(self.planeWidget.GetSlicePosition()+0.2)                
        self.planeWidget2.SetEnabled(1)
        self.planeWidget2.InteractionOff()
        
    def CreatePlaneWidget1(self, volume, windowlevel = None, colortable = None):
        range = volume.GetScalarRange()              
        self.planeWidget.SetInput(volume)
        self.planeWidget.SetPlaneOrientationToZAxes()
        #self.planeWidget1.SetInteractor(self.parent.main.renwini)
        self.planeWidget.SetEnabled(1)
        self.planeWidget.InteractionOn()        
        
    def GetColorTable_bw(self, range1, range2):
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(1.0, 1.0 )
        lut.SetAlphaRange(0.0,0.0)
        lut.SetSaturationRange(0, 1)
        lut.SetRange(range1, range2)
        lut.Build()
        return lut

    def GetColorTable_green(self, range1, range2):
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(.25, .25 )
        lut.SetAlphaRange(0.0,1.0)
        lut.SetSaturationRange(0, 1)
        lut.SetRange(range1, range2)
        lut.Build()
        return lut
        
    def GetColorTable_greenlines(self, range1, range2):
        lut = vtk.vtkLookupTable()
        #lut.SetValueRange (range1, range2)
        lut.SetTableRange (0, 2000)
        lut.SetValueRange (0, 50)
        lut.SetNumberOfColors(10)
        for i in range(0,8):
            lut.SetTableValue( i, (0.0,1.0,0.0,1.0))
        #lut.SetTableValue( 5, (0.0,1.0,0.0,1.0))
        lut.SetTableValue( 0, (0.0,1.0,0.0,0.0))
        lut.SetTableValue( 7, (0.0,1.0,0.0,1.0))
        lut.SetTableValue( 8, (0.0,1.0,0.0,1.0))
        lut.SetTableValue( 9, (0.0,1.0,0.0,1.0))

        lut.Build()
        return lut        
     
    def GetColorTable_blue(self, range1, range2):
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(.55, .55 )
        lut.SetAlphaRange(0.0,0.7)
        lut.SetSaturationRange(0, 1)
        lut.SetRange(range1, range2)
        lut.Build()
        return lut     
               
            
    def OnStoreVolume(self, event):
        dialog = wx.FileDialog(self, message='Choose a file', style=wx.SAVE|wx.OVERWRITE_PROMPT)
        if dialog.ShowModal() == wx.ID_OK:
            file = dialog.GetPath()
            #dir = dialog.GetDirectory()
            writer = vtk.vtkXMLImageDataWriter()
            writer.SetInput(self.volumecollection.GetItemAsObject(self.VolumeListbox.GetSelection()))
            writer.SetFileName(file)
            writer.Write()
            
    def OnLoadVolume(self, event):
        dialog = wx.FileDialog(self, message='Choose a file', style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            file = dialog.GetPath()
            #dir = dialog.GetDirectory()
            
            vti_reader = vtk.vtkXMLImageDataReader()
            vti_reader.SetFileName(file)
            vti_reader.Update()
            
            self.AddVolumeToListbox(vti_reader.GetOutput(), 'imported')

        
    def UnloadVolume(self):
        self.showSlicer.SetValue(False)
        self.showVolume.SetValue(False)
        self.showMuscle.Enable(False)
        self.showBone.Enable(False)
        self.showSkin.Enable(False)
        self.volumecollection.RemoveAllItems()
        self.VolumeListbox.Clear()
        
    def EnableVolume(self, bool):
        if bool == False:
            self.showVolume.Enable(False)
            self.showSlicer.Enable(False)
        else:
            self.showVolume.Enable(True)
            self.showSlicer.Enable(True)
            

    def OnclearFeedback(self, event):
        if(self.clearFeedback.IsChecked()==False):
            self.parent.geo_analysis.ClearLandmarks()
        else:
            self.parent.geo_analysis.ShowLandmarks()
            
    def OnvisualiseBoneChange(self, event, skiprender = False):
        self.parent.ren1.RemoveActor(self.parent.scapula_actor)
        self.parent.ren1.RemoveActor(self.parent.humerus_phantom)
        self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_glenoid)
        self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_humerus)
        self.parent.humerus_phantom.GetMapper().RemoveAllClippingPlanes()
        
        if self.visualiseBone.IsChecked()==False:
            self.showScapula.Enable(False)
            self.showHumerus.Enable(False)
            self.showGlenoidProsthesis.Enable(False)
            self.showHumerusProsthesis.Enable(False)
        else:
            if self.parent.modelloader.humerus_id != -1:
                self.showHumerus.Enable(True)
            if self.parent.modelloader.scapula_id != -1:
                self.showScapula.Enable(True)
            if self.parent.modelloader.humerus_prosthesis_id != -1:
                self.showHumerusProsthesis.Enable(True)
            if self.parent.modelloader.glenoid_prosthesis_id != -1:
                self.showGlenoidProsthesis.Enable(True)                
            
        if (self.showScapula.IsChecked()==True and self.visualiseBone.IsChecked()==True):
            self.parent.ren1.AddActor(self.parent.scapula_actor)
        if (self.showHumerus.IsChecked()==True and self.visualiseBone.IsChecked()==True):
            self.parent.ren1.AddActor(self.parent.humerus_phantom)
        if (self.showGlenoidProsthesis.IsChecked()==True and self.visualiseBone.IsChecked()==True):
            self.parent.ren1.AddActor(self.parent.actor_prosthesis_glenoid)
        if (self.showHumerusProsthesis.IsChecked()==True and self.visualiseBone.IsChecked()==True):
            self.parent.ren1.AddActor(self.parent.actor_prosthesis_humerus)
            if self.parent.humerus_phantom.GetPosition()!=(0.0, 0.0, 0.0):
                self.parent.humerus_phantom.GetMapper().AddClippingPlane(self.parent.planningmodule.cp1_humerus)
        if skiprender == False:
            self.parent.Render()

    def OnDecimatedChange(self, event):
        self.parent.main.panel1.OnCTChoice(event)
        
    def OnShowVolumeChange(self, event, skiprender = False):
        if self.volume_path != '' and self.volume_changed == True and self.showVolume.IsChecked()==True:
            self.volume_changed = False
            self.LoadVTI(skiprender)
            #self.my_thread = superthread.Thread( group=None, target=self.LoadVTI, args=() )
            #self.my_thread.start()
            
        if self.volume_path != '' and self.volume_changed == False:             
            shifter = vtk.vtkImageShiftScale()
            shifter.SetInput(self.parent.volumedata_resampled)
            shifter.SetShift(1000.0)
            shifter.SetOutputScalarTypeToUnsignedShort()

            # Create transfer mapping scalar value to opacity
            self.opacityTransferFunction.AddPoint(-10000, 0.0)

            self.opacityTransferFunction.AddPoint(1600, 0.0)
            
            
            # Create transfer mapping scalar value to color
            colorTransferFunction = vtk.vtkColorTransferFunction()
            colorTransferFunction.AddRGBPoint(900.0, 0.9, 0.7, 0.5)
            colorTransferFunction.AddRGBPoint(1000.0, 1.0, 1.0, 1.0)
            colorTransferFunction.AddRGBPoint(1064.0, 1.0, 0.0, 0.0)
            colorTransferFunction.AddRGBPoint(1128.0, 0.9, 0.9, 0.8)
            colorTransferFunction.AddRGBPoint(1192.0, 0.9, 0.9, 0.5)
            colorTransferFunction.AddRGBPoint(1255.0, 0.9, 0.7, 0.4)

            # The property describes how the data will look
            volumeProperty = vtk.vtkVolumeProperty()
            volumeProperty.SetColor(colorTransferFunction)
            volumeProperty.SetScalarOpacity(self.opacityTransferFunction)
            volumeProperty.ShadeOn()
            volumeProperty.SetInterpolationTypeToLinear()

            # The mapper / ray cast function know how to render the data
            compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
            volumeMapper = vtk.vtkVolumeRayCastMapper()
            volumeMapper.SetMinimumImageSampleDistance(2.0) # higher = faster
            volumeMapper.SetMaximumImageSampleDistance(2.0) # higher = faster
            volumeMapper.SetVolumeRayCastFunction(compositeFunction)
            volumeMapper.SetInputConnection(shifter.GetOutputPort())

            # The volume holds the mapper and the property and
            # can be used to position/orient the volume
            
            self.rendervolume.SetMapper(volumeMapper)
            self.rendervolume.SetProperty(volumeProperty)
            self.OnVolumeValuesChange(event)

        if(self.showVolume.IsChecked()==False):
            self.parent.ren1.RemoveVolume(self.rendervolume)
            self.showMuscle.Enable(False)
            self.showBone.Enable(False)
            self.showSkin.Enable(False)
        else:
            self.showMuscle.Enable(True)
            self.showBone.Enable(True)
            self.showSkin.Enable(True)            
            self.parent.ren1.AddVolume(self.rendervolume)            
        if skiprender == False:
            self.parent.Render()
        
    def OnVolumeValuesChange(self, event):
        self.opacityTransferFunction.RemoveAllPoints()
        self.opacityTransferFunction.AddPoint(-10000, 0.0)
        self.opacityTransferFunction.AddPoint(1600, 0.0)
        
        if(self.showBone.IsChecked()==False):
            self.opacityTransferFunction.AddPoint(1150, 0.0)
            self.opacityTransferFunction.AddPoint(1300, 0.0)
            self.opacityTransferFunction.AddPoint(1400, 0.0)
        else:
            self.opacityTransferFunction.AddPoint(1150, 1.0)
            self.opacityTransferFunction.AddPoint(1300, 1.0)
            self.opacityTransferFunction.AddPoint(1400, 0.2)

        if(self.showMuscle.IsChecked()==False):
            self.opacityTransferFunction.AddPoint(1000, 0.0)
            self.opacityTransferFunction.AddPoint(1100, 0.0)
        else:
            self.opacityTransferFunction.AddPoint(1000, 0.01)
            self.opacityTransferFunction.AddPoint(1100, 0.5)
        
        if(self.showSkin.IsChecked()==False):
            self.opacityTransferFunction.AddPoint(900, 0.0)
        else:
            self.opacityTransferFunction.AddPoint(900, 1.00)       
            
        self.opacityTransferFunction.Update()
        self.parent.Render()  



    


    def OnShowSlicer(self, event, skiprender = False):        
        if self.volume_path != '' and self.volume_changed == True and self.showSlicer.IsChecked()==True:
            self.volume_changed = False
            self.LoadVTI(skiprender)
            
        if self.volume_path != '' and self.volume_changed == False:            
            self.outline = vtk.vtkOutlineFilter()
            self.outline.SetInput(self.parent.volumedata)
            self.outlineMapper = vtk.vtkPolyDataMapper()
            self.outlineMapper.SetInputConnection(self.outline.GetOutputPort())
            self.outlineActor.SetMapper(self.outlineMapper)
                        
            self.planeWidget.DisplayTextOn()
            self.planeWidget.SetTextureInterpolate(1)
            self.planeWidget.TextureVisibilityOn()
            self.planeWidget.SetInput(self.parent.volumedata)
            self.planeWidget.SetInteractor(self.parent.main.renwini._Iren)
            self.planeWidget.PlaceWidget()
            self.planeWidget.SetWindowLevel(220,40,0)
            self.planeWidget.SetPlaneOrientationToZAxes()
            self.planeWidget.SetSliceIndex(0)
            self.planeWidget.SetPicker(self.picker)
            self.planeWidget.SetKeyPressActivationValue("x")
            
        if(self.showSlicer.IsChecked()==False):
            try:
                self.planeWidget.SetEnabled(0)
            except RuntimeError:
                #widget was not set up yet.
                pass
            self.parent.ren1.RemoveActor(self.outlineActor)        
        else:
            self.planeWidget.SetEnabled(1)   
            self.parent.ren1.AddActor(self.outlineActor)        
        if skiprender == False:
            self.parent.Render()         
        
        

    def OnActivated(self, event):
        self.parent.planningmodule.ResetPlanning()
        self.parent.ren1.RemoveActor(self.parent.humerus_phantom)
        self.parent.ren1.RemoveActor(self.parent.scapula_actor)
        self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_humerus)
        self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_glenoid)
        self.parent.humerus_phantom.GetMapper().RemoveAllClippingPlanes()
        
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.polydata)
        self.torsoactor = vtk.vtkActor()
        self.torsoactor.SetMapper(mapper)
        self.parent.ren1.AddActor(self.torsoactor)
        

        #self.LoadDICOM()
        self.LoadVTI()
        #self.LoadSTL()
        
        outline = vtk.vtkOutlineFilter()
        outline.SetInput(self.parent.volumedata)
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(outlineMapper)
        self.parent.ren1.AddActor(self.outlineActor)        
        self.parent.Render()
        
        
    def LoadDICOM(self):
        self.dicom = vtk.vtkDICOMImageReader()        
        #self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/8528558-vogel/CT_STX6/SE0003')
        self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/5909563-romijn/CT_STX1/SE0003')
        #self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/1433007-vermeulen/CT_STX7/SE0002')
        self.dicom.Update()
        self.dicom.FileLowerLeftOff()
        self.dicom.Update()
        
        self.parent.volumedata = self.dicom.GetOutput()
        
        
    def LoadSTL(self):
        reader = vtk.vtkSTLReader()
        reader.SetFileName(self.parent.modelloader.path+"ct/torso/vogel_glenoidtest_export.stl")
        self.polydata = reader.GetOutput()
        self.RenewPolyData()
        
    def LoadVTI(self, skiprender = False): #*args, 
        
        self.vti_reader = vtk.vtkXMLImageDataReader()
        filename = self.volume_path
        #filename = self.parent.modelloader.path+"ct/torso/vogel_glenoidtestsleutelbeen.vti"
        #filename = self.parent.modelloader.path+"ct/torso/vogel.vti"
        #filename = self.parent.modelloader.path+"ct/torso/romijn_glenoidtest.vti"
        #filename = self.parent.modelloader.path+"ct/torso/romijn.vti"
        #filename = self.parent.modelloader.path+"ct/torso/vermeulen.vti"
        self.vti_reader.SetFileName(filename)
        self.vti_reader.Update()
        
        
        #factor = 0.75
        #factor = 0.65              
        self.parent.volumedata = self.vti_reader.GetOutput()
        self.parent.volumedata.Update()
        self.parent.volume_dimensions = self.parent.volumedata.GetDimensions()
        self.parent.volume_spacing = self.parent.volumedata.GetSpacing()
        self.parent.volume_extent = self.parent.volumedata.GetExtent()
        
        print "Dimensions: ", self.parent.volume_dimensions
        print "Spacing: ", self.parent.volume_spacing
        print "Extent: ", self.parent.volume_extent
        
        self.GaussianVolume()
        self.ResampleVolume()
              
        self.edgevolume = vtk.vtkImageData()
        self.edgevolume.SetDimensions(self.parent.volume_dimensions)
        self.edgevolume.SetSpacing(self.parent.volume_spacing)
        self.edgevolume.SetScalarTypeToFloat()
        self.edgevolume.AllocateScalars()
        
        self.AddVolumeToListbox(self.parent.volumedata, "original volume")
        self.AddVolumeToListbox(self.parent.volumedata_resampled, "resampled volume")
        if skiprender == False:
            self.parent.Render()        
        
    def ResampleVolume(self):
        self.parent.resample_factor = 0.65
        self.resample = vtk.vtkImageResample()
        self.resample.SetAxisMagnificationFactor(0, self.parent.resample_factor)
        self.resample.SetAxisMagnificationFactor(1, self.parent.resample_factor)
        self.resample.SetAxisMagnificationFactor(2, self.parent.resample_factor)
        self.resample.SetInput(self.parent.volumedata_gaussian)
        self.parent.volumedata_resampled = self.resample.GetOutput()
        self.parent.volumedata_resampled.Update()
        self.parent.resampled_dimensions = self.parent.volumedata_resampled.GetDimensions()
        self.parent.resampled_spacing = self.parent.volumedata_resampled.GetSpacing()
        self.parent.resampled_extent = self.parent.volumedata_resampled.GetExtent()
        
    def GaussianVolume(self):
        deviation = 1.0
        radius = 1.0
        smooth_vol = vtk.vtkImageGaussianSmooth()
        smooth_vol.SetDimensionality(3)
        smooth_vol.SetInput(self.parent.volumedata)
        smooth_vol.SetStandardDeviation (deviation, deviation, deviation)
        smooth_vol.SetRadiusFactors (radius, radius, radius)
        smooth_vol.Update()
        self.parent.volumedata_gaussian = self.SharpenVolume(smooth_vol.GetOutput())
        #self.parent.volumedata_gaussian = smooth_vol.GetOutput()
        
    def SharpenVolume(self, volume):
        a1 = vtk.vtkImageGradientMagnitude()
        a1.SetDimensionality(3)
        a1.SetInput(volume)
        a1.Update()
        a2 = vtk.vtkImageMathematics()
        a2.SetOperationToAdd()
        a2.SetInput1(a1.GetOutput())
        a2.SetInput2(volume)
        a2.Update()
        
        b1 = vtk.vtkImageGradientMagnitude()
        b1.SetDimensionality(3)
        b1.SetInput(a2.GetOutput())
        b2 = vtk.vtkImageMathematics()
        b2.SetOperationToSubtract()
        b2.SetInput1(a2.GetOutput())
        b2.SetInput2(b1.GetOutput())
        b2.Update()
        
        c2 = vtk.vtkImageMathematics()
        c2.SetOperationToAdd()
        c2.SetInput1(a1.GetOutput())
        c2.SetInput2(b2.GetOutput())
        c2.Update()
        
        return c2.GetOutput()

        
    def RebuildPolydata(self, event=0, thresholdmin=125.0, thresholdmax=2500.0):
        threshold = vtk.vtkImageThreshold()
        threshold.SetInput(self.parent.volumedata)
        threshold.ThresholdBetween(thresholdmin, 2500.0)
        threshold.SetInValue(1.0)
        threshold.ReplaceInOn()
        threshold.SetOutValue(0.0)
        threshold.ReplaceOutOn()
        threshold.Update()
        print "Thresholding finished."
        mc = vtk.vtkMarchingContourFilter()
        mc.SetInput(threshold.GetOutput())
        mc.ComputeScalarsOff()
        mc.ComputeGradientsOff()
        mc.ComputeNormalsOff()
        mc.Update()
        self.polydata = mc.GetOutput()
        self.RenewPolyData()
        print "Marching cubes finished."
        TriangleFilter = vtk.vtkTriangleFilter()
        TriangleFilter.SetInput(mc.GetOutput())
        TriangleFilter.Update()
        self.polydata = TriangleFilter.GetOutput()
        self.RenewPolyData()
        print "Triangle filter finished."
        Decimated = vtk.vtkDecimatePro()
        Decimated.SetFeatureAngle(15.0)
        Decimated.SetTargetReduction(0.98)
        Decimated.PreserveTopologyOn()
        Decimated.SetInput(TriangleFilter.GetOutput())
        Decimated.Update()
        self.polydata = Decimated.GetOutput()
        self.RenewPolyData()
        print "Decimate finished."
        Smooth = vtk.vtkSmoothPolyDataFilter()
        Smooth.SetInput(Decimated.GetOutput())
        Smooth.SetNumberOfIterations(50)
        Smooth.SetRelaxationFactor(0.10) 
        Smooth.Update()
        self.polydata = Smooth.GetOutput()
        self.RenewPolyData()
        print "Smooth finished."  
        
        
        Normals = vtk.vtkPolyDataNormals()
        Normals.SetInput(Smooth.GetOutput())
        #Normals.SetFeatureAngle(60.0)
        Normals.SplittingOff()
        Normals.ConsistencyOff()
        #Normals.AutoOrientNormalsOn()
        self.polydata = Normals.GetOutput()
        self.RenewPolyData()
        
        #~ self.splitextractor.SetUp()
        #~ print self.splitextractor.GetNeighbouringVertices(13882)
        #self.parent.VisualisePoint(self.polydata.GetPoint(13882), "1",(0.8,0.8,1),1)

    def OnRecordViewToggle(self, event):
        pass

        